package com.soul.admin.listener;

import com.soul.autoconfig.template.AliyunGreenTemplate;
import com.soul.dubbo.api.mongo.MovementApi;
import com.soul.model.mongo.Movement;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author mdoya
 * @version 1.0
 * @description: 动态发布监听
 */
@Slf4j
@Component
public class MovementListener {

    @DubboReference
    private MovementApi movementApi;

    @Autowired
    private AliyunGreenTemplate aliyunGreenTemplate;

    /**
     *  rabbitmq消息队列 监听生产者消息
     * @param movementId 发布动态主键
     */
    @RabbitListener(
            bindings = @QueueBinding( // 消息队列绑定
                    value = @Queue(value = "soul.audit.queue",durable = "true"), // 消息队列名称  durable持久化
                    exchange = @Exchange(value = "soul.audit.exchange",type = ExchangeTypes.TOPIC),  // 绑定生产者交换机，交换机类型为主题模式    简单  广播 路由 主题 订阅模式 *匹配一个  #匹配一个或者多个
                    key = {"audit.movement"} // 绑定key  指定交换机名称 路径可以完全限定或者*或者#
            )
    )
    public void listenerMessage(String movementId){
        log.debug("开始发布动态审核监听");
        Movement movement = movementApi.findById(movementId);
        if (movement != null){
            try {
                // 审核图片
                Map<String, String> imageMap = aliyunGreenTemplate.imageScan(movement.getMedias());
                // 审核内容
                Map<String, String> textMap = aliyunGreenTemplate.greenTextScan(movement.getTextContent());
                // 审核状态校验
                Integer state = 0; // 动态内容状态
                if (imageMap != null && textMap != null){
                    String imageSuggestion = imageMap.get("suggestion");
                    String textSuggestion = textMap.get("suggestion");
                    if ("block".equals(imageSuggestion) || "block".equals(textSuggestion)){
                        state = 2;
                    } else if ("pass".equals(imageSuggestion) && "pass".equals(textSuggestion)){
                        state = 1;
                    }
                }
                // 修改发布动态审核状态
                movementApi.updateById(movementId,state);
            } catch (Exception e) {
                log.error("发布动态审核失败: {}" + movementId);
            }
        }
        log.debug("结束发布动态审核监听");
    }
}
